<script setup>
import { h, ref } from 'vue'
import { VChip, VSwitch } from 'vuetify/components'

import { getUsers, createUser, updateUser, deleteUser, deleteBatch } from '@/api/users.js'
import DataTable from '@/components/DataTable.vue'
import UserEditDialog from '@/components/UserEditDialog.vue'
import UserInfoDialog from '@/components/UserInfoDialog.vue'

const headers = [
  { title: '用户名', key: 'username' },
  { title: '邮箱', key: 'email' },
  { title: '角色', key: 'roles' },
  { title: '状态', key: 'status' },
  { title: '创建时间', key: 'createdAt' },
  { title: '更新时间', key: 'updatedAt' },
  { title: '操作', key: 'actions', sortable: false },
]

const usersApi = {
  fetch: getUsers,
  create: createUser,
  delete: deleteUser,
  deleteBatch: deleteBatch,
}

const slots = {
  status: (item) => {
    return h(VSwitch, {
      modelValue: item.status === 1,
      color: item.status === 1 ? 'success' : 'error',
      hideDetails: true,
      density: 'compact',
      'onUpdate:modelValue': async (value) => {
        try {
          await updateUser({ ...item, status: value ? 1 : 0 })
          refreshTrigger.value++
        } catch (error) {
          console.error('Failed to update user status:', error)
        }
      },
    })
  },
  roles: (item) => {
    console.log(item.roles)
    return h(
      'div',
      { class: 'd-flex flex-wrap' },
      item.roles.map((role) => h(VChip, { color: 'primary', variant: 'flat' }, role.description)),
    )
  },
}

const tableRef = ref()
const showDialog = ref(false)
const showInfoDialog = ref(false)
const editingUser = ref(null)
const viewingUser = ref(null)
const refreshTrigger = ref(0)
const selectedUsers = ref([])

const openEdit = (user) => {
  editingUser.value = user
  showDialog.value = true
}

const openCheck = (user) => {
  viewingUser.value = user
  showInfoDialog.value = true
}

const handleSave = async (formData) => {
  if (editingUser.value) {
    await updateUser(formData)
  } else {
    await createUser(formData)
  }
  refreshTrigger.value++
}
</script>

<template>
  <h1>用户管理</h1>
  <v-spacer />
  <v-card-text>
    <DataTable
      ref="tableRef"
      v-model:selected="selectedUsers"
      :headers="headers"
      :downloadable="false"
      :api="usersApi"
      :refresh-trigger="refreshTrigger"
      :slots="slots"
      @edit="openEdit"
      @create="openEdit(null)"
      @check="openCheck"
    />
  </v-card-text>

  <UserEditDialog v-model="showDialog" :user="editingUser" @submit="handleSave" />
  <UserInfoDialog v-model="showInfoDialog" :user="viewingUser" />
</template>
